package com.xbongbong.paas.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.pojo.dto.ApplicationListDTO;
import com.xbongbong.paas.pojo.vo.ApplicationListVO;
import com.xbongbong.paas.service.PaasAppService;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.XbbProConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Objects;

/**
 * @author: wufeng
 * @date: 2018/9/12 9:16
 * @desrcption: 手机应用管理
 */
@RestController
@RequestMapping(XbbProConstant.API_ROOT_PREFIX + "/mobile/application")
public class MobilePaasAppController {

    @Resource
    private PaasAppService paasAppService;

    /**
     * 根据对象applicationListDTO中的corpid 公司id查询对应的应用
     * @author wufeng
     * @date 2018/8/29 16:21
     * @param applicationListDTO
     * @param br
     * @descption
     * @return java.lang.String
     */
    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String list(@RequestBody @Valid ApplicationListDTO applicationListDTO, BindingResult br) throws Exception {
        XbbResponse<ApplicationListVO> response;
        if (br.hasErrors()) {
            String errMsg = Objects.requireNonNull(br.getFieldError()).getDefaultMessage();
            response = new XbbResponse<>(SystemErrorCodeEnum.API_ERROR_100002, errMsg);
        } else {
            try {
                ApplicationListVO applicationListVO = paasAppService.listPaasApp(applicationListDTO);
                response = new XbbResponse<>(applicationListVO, applicationListVO.getAppList().size());
            } catch (XbbException e){
                response = new XbbResponse<>(e);
            }
        }
        return JSON.toJSONString(response);
    }
}
